<template>
  <div class="monitor-box">
    <div class="left-box">
      <div class="control-box">
        <div class="search-box box-shadow">
          <a-form>
            <a-form-item label="标段">
              <a-select
                  v-model:value="cellQueryFormState.sections[0].sectionId"
                  @change="((val) => {changeSelect(val)})"
              >
                <a-select-option
                    v-for="section in sections"
                    :key="section.sectionId" :value="section.sectionId">
                  {{ section.sectionName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="仅显示当日施工单元">
              <a-switch
                  :defaultChecked="cellQueryFormState.workToday == 1"
                  @change="() => {cellQueryFormState.workToday = cellQueryFormState.workToday == 1 ? undefined : 1}"/>
            </a-form-item>
            <a-form-item label="单元状态">
              <a-select v-model:value="cellQueryFormState.status">
                <a-select-option
                    v-for="cellStatus in cellStatusDict.dict2"
                    :key="cellStatus.statusCode" :value="cellStatus.statusCode">
                  {{ cellStatus.statusName }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="单元名称">
              <a-input v-model:value="cellQueryFormState.cellName"></a-input>
            </a-form-item>
            <a-form-item>
              <a-button @click="selectSectionClick" type="primary">查询</a-button>
            </a-form-item>
          </a-form>
        </div>
        <div class="map-control box-shadow">
          <a-checkbox-group
              v-model:value="baseControl"
              @change="clickMapControl">
            <span class="map-control-title">基础数据</span>
            <a-row>
              <a-col :span="12">
                <a-checkbox value="border">单元边界</a-checkbox>
              </a-col>
            </a-row>
            <span class="map-control-title">水泥搅拌桩数据</span>
            <a-row>
              <a-row>
                <a-col :span="12">
                  <a-checkbox value="design">设计点</a-checkbox>
                </a-col>
                <a-col :span="12">
                  <a-checkbox value="fact">施工点</a-checkbox>
                </a-col>
              </a-row>
              <a-col :span="12">
                <a-checkbox value="real_cement">实时数据</a-checkbox>
              </a-col>
            </a-row>
          </a-checkbox-group>
        </div>
      </div>
      <div class="cell-table-box box-shadow">
        <div class="table-box-header">
          单元列表
        </div>
        <div class="table-box-center">
          <a-table
              :scroll="{ y: setHeight('.table-box-center', 125) + 'px' }"
              :data-source="cellBaseInfoList.cellInfo"
              :rowKey="record => record.cellId"
              @change="getCellBaseInfoList"
              :pagination="{
              current: cellBaseInfoList.startPage,
              total: cellBaseInfoList.totalCount,
              pageSize: cellBaseInfoList.everyPage,
              showLessItems: true}">
            <a-table-column title="归属标段" data-index="sectionName"></a-table-column>
            <a-table-column title="单元名称" data-index="cellName"></a-table-column>
            <a-table-column title="工艺类型" data-index="kind" width="80px">
              <template #default="{text}">
                <div>{{ kindDict.getNameByCode(text) }}</div>
              </template>
            </a-table-column>
            <a-table-column title="历史回放" data-index="cellId" width="80px">
              <template #default="{text,record}">
                <div class="table-icon-box">
                  <div @click="openPlaybackModal(text)">
                    <HistoryOutlined/>
                  </div>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="操作" data-index="cellId" width="50px">
              <template #default="{text,record}">
                <div class="table-icon-box">
                  <div @click="handleCell(record)">
                    <EditOutlined />
                  </div>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="启停" data-index="cellStatus" width="50px">
              <template #default="{text,record}">
                <a-switch :defaultChecked="text != 0" @change="setCellStatus(record)"/>
              </template>
            </a-table-column>
          </a-table>
        </div>
      </div>
    </div>
    <div class="right-box">
      <div class="base-info-box box-shadow">
        <a-descriptions :column="4">
          <a-descriptions-item label="单元名称" :span="1">
            {{ inCellBaseInfo ? inCellBaseInfo.cellName : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间" :span="1">
            {{ inCellBaseInfo ? inCellBaseInfo.gtmCreateTime : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="工艺类型" :span="1">
            {{inCellBaseInfo ? kindDict.getNameByCode(inCellBaseInfo.kind) : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="归属标段" :span="1">
            {{ inCellBaseInfo ? inCellBaseInfo.sectionName : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="区域面积" :span="1">
            {{ inCellBaseInfo ? inCellBaseInfo.area : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建账号" :span="1">
            {{ inCellBaseInfo ? inCellBaseInfo.userName : '--' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
      <div class="map-box box-shadow">
        <div class="map-event-control">
          <div @click="clickMapEvent" :class="{'map-control-button': true,'map-control-active': cementPointInfo.active}">水泥搅拌桩</div>
        </div>
        <div class="point-info" v-show="cementPointInfo.show">
          <div class="point-header">
            <span>水泥搅拌桩</span>
            <CloseOutlined @click="cementPointInfo.show = false"/>
          </div>
          <div class="point-content">
            <div class="info-box">
              <div class="real-time">
                <span>实时信息</span>
                <div class="info">
                  <a-row>
                    <a-col :span="4">机械名称</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.deviceName}}</a-col>
                    <a-col :span="4">深度</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.depth}}m</a-col>
                    <a-col :span="4">设备编号</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.deviceSn}}</a-col>
                    <a-col :span="4">电流</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.electricity}}A</a-col>
                    <a-col :span="4">桩孔坐标</a-col>
                    <a-col :span="8">{{cementPointInfo.coord}}</a-col>
                    <a-col :span="4">状态</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.status}}</a-col>
                    <a-col :span="4">搅拌次数</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.mixCount}}次</a-col>
                    <a-col :span="4">桩号</a-col>
                    <a-col :span="8">{{cementPointInfo.pointName}}</a-col>
                    <a-col :span="4">喷浆流量</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.shootAmentUnit}}m³</a-col>
                    <a-col :span="4">速度</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.speed}}m/s</a-col>
                    <a-col :span="4">累计流量</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.shootAmentBuild}}m³</a-col>
                    <a-col :span="4">时间</a-col>
                    <a-col :span="8">{{cementRealTimeInfo.gtmTime}}</a-col>
                  </a-row>
                </div>
              </div>
              <div class="pile-forming">
                <span>成桩信息</span>
                <div class="info">
                  <a-row>
                    <a-col :span="4">机械名称</a-col>
                    <a-col :span="8">{{cementPointInfo.deviceName}}</a-col>
                    <a-col :span="6">桩号</a-col>
                    <a-col :span="6">{{cementPointInfo.pointName}}</a-col>
                    <a-col :span="4">设备编号</a-col>
                    <a-col :span="8">{{cementPointInfo.deviceSn}}</a-col>
                    <a-col :span="6">平均喷浆停留时间</a-col>
                    <a-col :span="6">{{cementPointInfo.shootAvgTime}}s</a-col>
                    <a-col :span="4">桩孔坐标</a-col>
                    <a-col :span="8">{{cementPointInfo.coord}}</a-col>
                    <a-col :span="6">平均倾斜度</a-col>
                    <a-col :span="6">{{cementPointInfo.titleAvg}}</a-col>
                    <a-col :span="4">搅拌深度</a-col>
                    <a-col :span="8">{{cementPointInfo.mixDepth}}m</a-col>
                    <a-col :span="6">平均搅拌升降速度</a-col>
                    <a-col :span="6">{{cementPointInfo.mixAvgSpeed}}m/s</a-col>
                    <a-col :span="4">搅拌次数</a-col>
                    <a-col :span="8">{{cementPointInfo.mixCount}}次</a-col>
                    <a-col :span="6">平均喷浆升降速度</a-col>
                    <a-col :span="6">{{cementPointInfo.shootAvgSpeed}}m/s</a-col>
                    <a-col :span="4">喷浆次数</a-col>
                    <a-col :span="8">{{cementPointInfo.shootCount}}次</a-col>
                    <a-col :span="6">材料用量</a-col>
                    <a-col :span="6">{{cementPointInfo.amount}}</a-col>
                  </a-row>
                </div>
              </div>
            </div>
            <div class="option-box">
              <div class="pb-header-box">
                <vue-echarts :option="cementBuildOption" style="width: 631px; height: 543px;" ref="chart"/>
              </div>
            </div>
          </div>
        </div>
        <div @click="openExAreaModal(inCellBaseInfo ? inCellBaseInfo.cellId : 0)" class="ex-area-btn"/>
        <div @click="workListInfo.showModal = true" class="work-list-btn" />
        <div class="tamp-legend">
          <div>
            <div class="legend">
              <div style="background: #0C7798"></div>
            </div>
            <div class="legend-title">设计点</div>
          </div>
          <div>
            <div class="legend">
              <div style="background: #0CDB34"></div>
            </div>
            <div class="legend-title">施工点</div>
          </div>
        </div>
        <div id="mapboxgl-box"></div>
        <div class="draw-save" v-if=isDrawSave>
          <a-button type="default" shape="square" @click="saveDrawArea" size="middle">
            <template #icon><CheckOutlined /></template>
          </a-button>
        </div>
      </div>
    </div>
  </div>
  <SModal
      title="历史回放"
      width="906"
      height="644"
      :isShow="playbackInfo.showPbModal"
      @closed="closePlaybackModal()"
      forceRender="true"
  >
    <div class="pb-track-modal">
      <div class="pb-header-box">
        <span style="font-size: 14px;">起止时间：</span>
        <a-range-picker
            v-model:value="playbackDate"
            :ranges="ranges"
            :show-time="{
            defaultValue: [
              moment('00:00:00', 'HH:mm:ss'),
              moment('23:59:59', 'HH:mm:ss')
            ]
          }"
        />
        <a-button
            type="primary"
            @click="
            getPath(playbackInfo.cellId, playbackDate[0], playbackDate[1])
          "
            style="margin-left: 40px"
        >查询
        </a-button
        >
      </div>
      <div class="pb-track-box ">
        <div id="trackpb-box"></div>
        <div class="map-event-control">
          <div @click="startClick" class="map-control-button">开始</div>
          <div @click="pauseClick" class="map-control-button">启停</div>
          <div @click="stopClick" class="map-control-button">停止</div>
        </div>
      </div>
    </div>
  </SModal>
  <SModal
      title="工作设备列表"
      width="480"
      :is-show="workListInfo.showModal"
      @closed="() => (workListInfo.showModal = false)">
    <div class="smodal-box smodal-to-cell">
      <a-table
          :scroll="{ y: `205px` }"
          :data-source="workListInfo.workList"
          :rowKey="record => record.deviceId"
          @change="getToNextCellDevice"
          :pagination="false">
        <a-table-column title="机械编号" data-index="deviceSn"></a-table-column>
        <a-table-column title="机械名称" data-index="deviceName"></a-table-column>
        <a-table-column title="机械类型" data-index="deviceKind">
          <template #default="{text}">
            <div>{{ deviceTypeDict.getNameByCode(text) }}</div>
          </template>
        </a-table-column>
      </a-table>
    </div>
  </SModal>
  <SModal
      title="排除区域"
      width="900"
      height="362"
      :is-show="showExModal"
      @closed="()=>{showExModal = false}">
    <div class="ex-area-modal">
      <div class="ex-table-box">
        <a-table
            :scroll="{y:'180px'}"
            :data-source="exAreaList"
            :pagination="false">
          <a-table-column title="排除时间" data-index="gtmCreateTime" width="120px"/>
          <a-table-column title="操作人员" data-index="userName" width="100px"/>
          <a-table-column title="排除区域名称" data-index="excludedName" width="160px">
            <template #default="{text,record}">
              <div style="padding: 0 8px">
                <a-input v-model:value="record.excludedName" v-if="record.excludedId<0"/>
                <span v-else>{{text}}</span>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="排除原因" data-index="reason">
            <template #default="{text,record}">
              <div style="padding: 0 8px">
                <a-input v-model:value="record.reason" v-if="record.excludedId<0"/>
                <span v-else>{{text}}</span>
              </div>
            </template>
          </a-table-column>
          <a-table-column
              title="绘制范围"
              width="100px"
              data-index="excludedId">
            <template #default="{text,record}">
              <a-button
                  @click="drawTheBorder(record)"
                  :disabled="record.excludedId > 0"
                  type="primary"
                  ghost>绘制</a-button>
            </template>
          </a-table-column>
          <a-table-column title="操作" width="60px" data-index="excludedId">
            <template #default="{text,record,index}">
              <div class="table-icon-box" style="padding: 0 5px; font-size: 16px">
                <div v-if="text<=0" @click="saveExArea(record)">
                  <SaveOutlined/>
                </div>
                <div v-if="text<=0" @click="delExArea(record,index)">
                  <DeleteOutlined/>
                </div>
                <div v-if="text>0" @click="delExArea(record,index)">
                  <DeleteOutlined/>
                </div>
              </div>
            </template>
          </a-table-column>
        </a-table>
      </div>
      <div class="ex-area-btn-box"><a-button @click="addExArea" type="primary">新增</a-button></div>
    </div>
    <input
        id="read-ex-area-input"
        @change="readBorderFile"
        accept=".txt"
        type="file"
        style="position:absolute;width:0;height:0;opacity:0"/>
  </SModal>
</template>

<script lang="ts">
import {defineComponent, reactive, ref, toRefs, onMounted, onBeforeUnmount, nextTick} from "vue";
import {createLogger, useStore} from "vuex";
import {setHeight} from "@/utils/tableUtils"
import { cellBaseInfo } from "@/hooks/cell/index"
import kindDict from "@/dicts/kindDict"
import cellStatusDict from "@/dicts/cellStatusDict"
import mapboxgl, { AnyLayer, LngLat, Marker, Sources } from "mapbox-gl"
import {
  EditOutlined,
  SaveOutlined,
  DeleteOutlined,
  CloseOutlined,
  CheckOutlined,
  HistoryOutlined
} from '@ant-design/icons-vue'
import {message} from "ant-design-vue"
import axios from "axios"
import qs from "qs"
import redLine from "@/assets/data/redLine.ts"
import "mapbox-gl/dist/mapbox-gl.css"
import {MqttOptions,MqttService} from "@/utils/mqttService"
import config from "@/config/index"
import SModal from "@/components/SModal/index.vue"
import deviceTypeDict from "@/dicts/deviceTypeDict"
import moment, {Moment} from 'moment'
import lodash from "lodash"
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import {VueEcharts} from 'vue3-echarts';
import * as turf from "@turf/turf";

interface MapLayerRequestInfo{
  craft: string | null
  cellId: number | null
  type: string | null
}
class CementPointInfo {
  cellId = -1
  cellName = ""
  deviceName = ""  // 机械名称
  deviceSn = ""  // 设备编号
  pointName = ""  // 桩号
  id = <any>undefined // 设计点id
  coord = <any>undefined  // 桩孔坐标
  mixDepth = <any>undefined  // 搅拌深度
  mixCount = <any>undefined  // 搅拌次数
  shootCount = <any>undefined  // 喷浆次数
  shootAvgTime = <any>undefined  // 平均喷浆停留时间
  titleAvg = <any>undefined  // 平均倾斜度
  mixAvgSpeed = <any>undefined  // 平均搅拌升降速度
  shootAvgSpeed = <any>undefined  // 平均喷浆升降速度
  amount = <any>undefined  // 材料用量
  active = false
  show = false // cement-修改---已修改
}
interface MapDeviceInfo {
  deviceId: number
  deviceInfo: any
  deviceMarker: Marker
}

export default defineComponent({
  setup() {
    const store = useStore()
    const userName = ref(JSON.parse(JSON.stringify(store.getters['userinfo/getUserInfo'])).username)
    const sections = ref(JSON.parse(JSON.stringify(store.getters['userinfo/getUserSection'])))

    let isRedrawKind = ref(false)
    let isRedrawAction = ref(false)

    // 水泥搅拌桩施工数据关系图
    const resultList:any = ref({});
    const cementBuildOption: any = ref(null);
    // 水泥搅拌桩实时数据
    const pointRealTimeInfo:any = ref({})
    const cementRealTimeInfo:any = ref({})
    //显示保存按钮
    let isDrawSave = ref(false)
    const {
      cellQueryFormRef, cellQueryFormState, cellBaseInfoList, inCellBaseInfo,
      getCellBaseInfoList, setCellStatus, getCellBaseInfo
    } = cellBaseInfo()

    const playbackInfo = reactive({
      cellId: -1,
      showPbModal: false
    })
    const playbackDate = ref<Moment[]>([
      moment('00:00:00', 'HH:mm:ss'),
      moment('23:59:59', 'HH:mm:ss')
    ])

    cellQueryFormState.value.sections[0].kind = [22]
    const workListInfo = ref({
      showModal: false,
      workList: new Array<any>()
    })
    const mapControl = reactive({
      baseControl: new Array<string>(),
      cementPointInfo: new CementPointInfo()
    })
    const exAreaInfo = reactive({
      uploadFileRecord: <any>null,
      showExModal: false,
      exAreaList: new Array<any>()
    })

    const realMapInfo = reactive({
      deviceList: new Array<MapDeviceInfo>(), // 设备信息列表(主要用于marker)
      realSourceName: 'real_cement',
      realSource: { // 实时施工数据源列表
        type: 'FeatureCollection',
        features: new Array<any>()
      },
      realLayerName: 'real_cement', // 实时施工图层列表
      subscribeList: new Array<string>() // 订阅设备列表
    })
    // 看板跳转
    const zoneId:any = ref(null)
    const zoneKind:any = ref(null)

    let maps:any
    let trackMap:any

    let newMap: any

    let routeId: any = []
    let realRouteId: any = []
    let animatePointId:any =[]
    // 初始化地图
    const initMap = () => {
      mapboxgl.accessToken = config.map.accessToken
      let mapSource: Sources = {
        google: {
          type: 'raster',
          tiles: [
            config.map.baseLayer1URL,
          ],
          tileSize: 256
        }
      }
      let layers: AnyLayer[] = [
        {
          id: 'google-tiles1',
          type: 'raster',
          source: 'google'
        }
      ]
      maps = {
        map: new mapboxgl.Map({
          container: 'mapboxgl-box',
          style: {
            version: 8,
            sources: mapSource,
            layers: layers
          },
          minZoom: 5,
          maxZoom: 20,
          center: config.map.center,
          zoom: config.map.zoom,
          attributionControl: false
        }),
        sourceList: new Set<string>(),
        LayerList: new Set<string>()
      }

      maps.map.on('load', () => {
        if (zoneId.value == null || zoneKind.value == null) {
          maps.map.addLayer({
            id: "satellite1",
            type: "raster",
            source: {
              type: "raster",
              tiles: [config.map.baseLayer2URL],
            },
          })
          maps.map.addLayer({
            id: 'air',
            type: 'raster',
            source: {
              type: 'raster',
              tiles: [config.map.airUrl]
            }
          })
          maps.map.addSource('redLineSource', { type: 'geojson', data: redLine })
          maps.map.addLayer({
            id: 'redLineLayer',
            type: 'line',
            source: 'redLineSource',
            layout: {},
            paint: {
              'line-color': '#ff0000',
              'line-width': 2,
              'line-opacity': 1
            }
          })
        }
      })
      maps.map.on("click", (e:any)=> {
        if (mapControl.cementPointInfo.active) {
          getGetPointTimes(e.lngLat.lat, e.lngLat.lng).then((res: any) => {
            mapControl.cementPointInfo = new CementPointInfo()
            cementRealTimeInfo.value = {}
            mapControl.cementPointInfo.cellName = inCellBaseInfo.value.cellName
            if (res.data != null) {
              Object.assign(mapControl.cementPointInfo,res.data)
              mapControl.cementPointInfo.show = true
              // for (let i = 0; i < pointRealTimeInfo.value.length; i++){
              //   console.log("循环")
              //   console.log(pointRealTimeInfo.value[i])
              //     if(pointRealTimeInfo.value[i].id == mapControl.cementPointInfo.id) {
              //     console.log("if判断！！！！！！！！！！！！！！！！！！！！！! ")
              //     cementRealTimeInfo.value = pointRealTimeInfo.value[i]
              //     console.log("=======================================")
              //     console.log(cementRealTimeInfo.value)
              //   }
              // }
              if(pointRealTimeInfo.value.id == mapControl.cementPointInfo.id) {
                cementRealTimeInfo.value = pointRealTimeInfo.value
                }
            } else {
              mapControl.cementPointInfo.show = false
            }
            mapControl.cementPointInfo.active = true
          })
        }
      })
    }
    const getGetPointTimes = (latitude:number,longitude:number)=>{
      return new Promise((resolve,reject)=>{
        if(!inCellBaseInfo.value){
          message.info("请先选择单元后再进行操作")
          return
        }
        let cellId = inCellBaseInfo.value.cellId
        axios.post("/cement/findPointInfo",  // cement-修改接口---已修改
            {cellId,latitude,longitude}).then((res:any)=>{
          resolve(res)
          mapControl.cementPointInfo = res.data
          getCementBuildInfo()
        }).catch((err:any)=>{
          reject(err)
        })
      })
    }
    // 添加图层
    const addLayer = (layerInfo: MapLayerRequestInfo, callback: Function | null = null) => {
      if (!maps.map) return
      maps.map.addLayer({
        id: `${layerInfo.type}`,
        type: 'raster',
        source: `${layerInfo.type}`,
        paint: {
          'raster-opacity': 1 // 图层显示透明度
        }
      })
      maps.LayerList.add(`${layerInfo.type}`)
    }
    // 添加数据源
    const addSource = (layerInfo: MapLayerRequestInfo, callback: Function | null = null) => {
      if (!maps.map) return
      maps.map.addSource(`${layerInfo.type}`, {
        type: 'raster',
        scheme: 'tms',
        tiles: [
          `${config.map.geoServer}${layerInfo.craft}%3A${layerInfo.cellId}_${layerInfo.type}@EPSG%3A900913@png/{z}/{x}/{y}.png`
        ],
        tileSize: 256
      })
      maps.sourceList.add(`${layerInfo.type}`)
    }
    // 移动地图视角
    const mapToCell = (cellCenter:LngLat)=>{
      if(!maps.map) return
      maps.map.jumpTo({center: cellCenter})
    }
    // 获取施工单元中正在工作设备列表
    const getCellWorkMachineryByCellId = (cell:any)=>{
      return new Promise((resolve, reject)=>{
        let data = {
          cellId: cell.cellId,
          kind: cell.kind
        }
        axios.post("common/findCellWorkMachineryByCellId",data).then((res:any)=>{
          resolve(res)
        }).catch((err:any)=>{
          reject(err)
        })
      })
    }
    // 列表中选择仓面
    const handleCell = (cell:any)=>{
      // removeDraw()
      let f1 = getCellBaseInfo(cell)
      let f2 = getCellWorkMachineryByCellId(cell)
      Promise.all([f1,f2]).then((res:any)=>{
        // 1.持久化数据
        // 清除旧图层&数据源
        maps.LayerList.forEach((item:any)=>{
          if(maps.map.getLayer(item)){
            maps.map.removeLayer(item)
            maps.LayerList.delete(item)
          }
        })
        maps.sourceList.forEach((item:any)=>{
          if(maps.map.getSource(item)) maps.map.removeSource(item)
        })
        // 添加默认图层
        let layerInfo:MapLayerRequestInfo = {
          cellId:inCellBaseInfo.value.cellId,
          craft:"HaErBin-JBZ",  // cement-修改-工艺代码---已修改
          type:"border"
        }
        addSource(layerInfo)
        addLayer(layerInfo)

        // 2.实时数据
        // 先清除旧的实时显示相关的数据,图层,marker
        realMapInfo.deviceList.forEach((item:any)=>{
          item.deviceMarker.remove()
        })
        realMapInfo.deviceList = new Array<MapDeviceInfo>()
        MqttService.unsubscribe(realMapInfo.subscribeList)
        realMapInfo.subscribeList = new Array<string>()
        realMapInfo.realSource.features = new Array<any>()
        if(maps.map.getLayer(realMapInfo.realLayerName)) maps.map.removeLayer(realMapInfo.realLayerName)
        if(maps.map.getSource(realMapInfo.realSourceName)) maps.map.removeSource(realMapInfo.realSourceName)

        // 订阅新选定仓面的设备数据
        workListInfo.value.workList = res[1].data
        res[1].data.forEach((item:any)=>{
          let el = document.createElement("div")
          el.className = "device-cement"
          el.innerText = `${item.deviceName}`

          realMapInfo.deviceList.push({
            deviceId:item.deviceId,
            deviceInfo:item,
            deviceMarker:new mapboxgl.Marker(el).setLngLat([0,0]).setOffset(new mapboxgl.Point(86,-16)).addTo(maps.map)
          })
          MqttService.subscribe(`${config.craft.cement.mqtt.topic}${item.deviceSn}`) // cement-修改-mqtt
        })

        // 3.操作界面
        mapControl.baseControl = ["border","real_cement"]
        // 跳转位置
        if (res[0].data.centLat && res[0].data.centLon){
          maps.map.setZoom(17)
          let cellCenter = new mapboxgl.LngLat(res[0].data.centLon, res[0].data.centLat);
          mapToCell(cellCenter)
        }
      })
    }
    // 点击图层控制按钮
    const clickMapControl = (res: any) => {
      if (!inCellBaseInfo.value) {
        message.info('请先选择单元后再进行操作')
        return
      }
      let diffList = res.concat(Array.from(maps.LayerList)).filter((cur: any, i: any, arr: any) => {
            return arr.indexOf(cur) === arr.lastIndexOf(cur)
      })
      diffList.forEach((item: any) => {
        let layerInfo: MapLayerRequestInfo = {
          cellId: inCellBaseInfo.value.cellId,
          craft: 'HaErBin-JBZ', //  cement-修改-工艺代码---已修改
          type: item
        }
        if (layerInfo.type != 'real_cement') {
          let layer = maps.map.getLayer(`${layerInfo.type}`)
          let source = maps.map.getSource(`${layerInfo.type}`)
          if (!layer && !source) {
            // 增加图层及数据源
            addSource(layerInfo)
            addLayer(layerInfo)
          } else if (layer && source) {
            // 移除图层
            maps.map.removeLayer(`${layerInfo.type}`)
            maps.LayerList.delete(`${layerInfo.type}`)
          } else if (!layer && source) {
            // 增加图层
            addLayer(layerInfo)
          }
        }
      })
      let realTampIndex = diffList.indexOf('real_cement')
      let realLayer = maps.map.getLayer('real_cement')
      if (!maps.map.getSource(realMapInfo.realSourceName)) maps.map.addSource(realMapInfo.realSourceName, {type: 'geojson', data: realMapInfo.realSource})
      if (realTampIndex >= 0 && realLayer) {
        // 若存在,删除
        maps.map.removeLayer('real_cement')
        maps.LayerList.delete(realMapInfo.realLayerName)
      } else if ((realTampIndex >= 0 && !realLayer) || realLayer) {
        // 若不存在,增加
        if (realLayer) maps.map.removeLayer('real_cement')
        maps.map.addLayer({
          id: realMapInfo.realLayerName,
          type: "circle",
          source: realMapInfo.realSourceName,
          paint: {
            'circle-radius': {
              'base': 2,
              'stops': [[0,0],[20,4]]  // 修改
            },
            'circle-color': "#0CDB34"
          }
        })
        maps.LayerList.add(realMapInfo.realLayerName)
      }
    }
    const clickMapEvent = ()=>{
      mapControl.cementPointInfo.show = false
      mapControl.cementPointInfo.active = !mapControl.cementPointInfo.active
    }
    // 打开排除区域弹框
    const openExAreaModal = (cellId: number) => {
      if (cellId <= 0) {
        message.info('请选择仓面后操作')
        return
      }
      axios.post('/common/findCellExcludeAreaByCellId', { cellId: cellId }).then((res: any) => {
        if (res.success) {
          exAreaInfo.exAreaList = res.data
          exAreaInfo.showExModal = true
        } else {
          message.info('获取排除信息失败')
        }
      })
    }
    // 重新绘制边界
    const createTiledMap = (cellId: number) => {
      return new Promise((resolve, reject) => {
        axios.post('/jbzMap/reCreatBorder', // cement-修改接口---已修改
            qs.stringify({
              cellID: cellId,
              workType: 1
            }),
            {
              headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then((res: any) => {
          resolve(res.success)
        })
      })
    }
    // 增加一列新的排除区域
    const addExArea = () => {
      exAreaInfo.exAreaList.push({
        cellId: inCellBaseInfo.value.cellId,
        excludedId: -1,
        excludedName: null,
        reason: null,
        userName: userName.value,
        border: { first: new Array(), second: new Array() },
        gtmCreateTime: moment().format('yyyy-MM-DD HH:mm:ss')
      })
    }

    let draw: any
    let drawData: any
    //绘制排除区域
    const drawTheBorder = (record: any) => {
      exAreaInfo.uploadFileRecord = record
      exAreaInfo.showExModal = false
      isDrawSave.value = true;
      initDraw()
    }
    //自定义绘图工具
    const initDraw = () => {
      draw = new MapboxDraw({
        displayControlsDefault: false,
        controls: {
          polygon: true,
          trash: true
        },
        defaultMode: 'draw_polygon'
      })
      maps.map.addControl(draw,"top-left")
      maps.map.on('draw.create', ()=>{
        drawData = draw.getAll();
      })
      maps.map.on('draw.delete', ()=>{
        drawData = draw.getAll();
      })
      maps.map.on('draw.update', ()=>{
        drawData = draw.getAll();
      })
      //添加
      maps.map.on('draw.modechange', ()=>{
        drawData = draw.getAll();
        if (draw.getMode() == 'draw_polygon') {
          let pids: any[] = []
          // ID of the added template empty feature
          const lid = drawData.features[drawData.features.length - 1].id
          drawData.features.forEach((f:any) => {
            if (f.geometry.type === 'Polygon' && f.id !== lid) {
              pids.push(f.id)
            }
          })
          draw.delete(pids)
        }
      })
    }
    // 保存绘制的区域
    const saveDrawArea = ()=>{
      exAreaInfo.showExModal = true
      removeDraw()
      // 0为 删除 2为第二个图形还没开始绘制
      if (drawData.features.length = 1){
        exAreaInfo.uploadFileRecord.border.first = new Array()
        exAreaInfo.uploadFileRecord.border.second = new Array()
        let feature = drawData.features[0]
        let geometry = feature!.geometry
        let coordinates = geometry!.coordinates
        if (coordinates.length>0){
          let borderAry = coordinates[0]
          if (borderAry.length>=1){
            for (let i = 0; i < borderAry.length-1; i++) {
              let pointAry = borderAry[i]
              exAreaInfo.uploadFileRecord.border.first.push(pointAry[0])
              exAreaInfo.uploadFileRecord.border.second.push(pointAry[1])
            }
          }
        }
      }
    }
    const removeDraw = ()=>{
      if (draw){
        maps.map.removeControl(draw)
        draw = null
      }
      isDrawSave.value = false;
    }

    // 保存排除区域
    const saveExArea = (record: any) => {
      if (lodash.isEmpty(record.excludedName) || lodash.trim(record.excludedName).length == 0) {
        message.info('请输入排除区域名称')
        return
      }
      if (record.border.first.length == 0) {
        message.info('请录入排除区域边界')
        return
      }
      axios.post('/common/saveCellExcludeAreaByCellId', {
        cellId: record.cellId,
        excludedId: record.excludedId,
        reason: record.reason,
        excludedName: record.excludedName,
        border: record.border
      }).then((res: any) => {
        if (res.success) {
          record.excludedId = res.data.excludedId
          createTiledMap(record.cellId)
          message.info('保存成功')
        } else {
          message.info(res.msg)
        }
      })
    }
    // 删除排除区域
    const delExArea = (record: any, index: number) => {
      if (record.excludedId > 0) {
        axios.post('/common/deleteCellExcludeAreaByCellId', {
          cellId: inCellBaseInfo.value.cellId,
          excludedId: record.excludedId
        }).then((res: any) => {
          if (res.success) {
            exAreaInfo.exAreaList.splice(index, 1)
            createTiledMap(inCellBaseInfo.value.cellId)
            removeDraw()
            message.info('删除成功')
          } else {
            message.info(res.msg)
          }
        })
      } else {
        exAreaInfo.exAreaList.splice(index, 1)
        createTiledMap(inCellBaseInfo.value.cellId)
        removeDraw()
        message.info('删除成功')
      }
    }
    // 打开文件选择框
    const openFileModal = (record: any) => {
      exAreaInfo.uploadFileRecord = record
      document.getElementById('read-ex-area-input')?.click()
    }
    // 读取边界数据
    const readBorderFile = () => {
      let inputDOM: any = document.getElementById('read-ex-area-input')
      let files = inputDOM.files

      if (files[0]) {
        let reader = new FileReader()
        reader.readAsText(files[0], 'UTF-8')
        reader.onload = (e: any) => {
          try {
            let fileStr = e.target.result
            let fileStrArr = fileStr.split(',,')
            exAreaInfo.uploadFileRecord.border.first = new Array()
            exAreaInfo.uploadFileRecord.border.second = new Array()

            for (let i = 0; i < fileStrArr.length; i++) {
              let pointArr = fileStrArr[i].split(',')
              if (pointArr.length == 2) {
                exAreaInfo.uploadFileRecord.border.first.push(parseFloat(pointArr[0]))
                exAreaInfo.uploadFileRecord.border.second.push(parseFloat(pointArr[1]))
              }
            }
          } catch (e) {
            message.warn('导入格式错误' + e)
            console.log(e)
          }
        }
        inputDOM.value = ''
      }
    }

    // 查询水泥搅拌桩电流深度折线图的相关数据
    const getCementBuildInfo = () =>{
      let idPoint = mapControl.cementPointInfo.id
      if (idPoint != null){
        axios.post("/cement/findHistory", {idPoint:idPoint}).then((res:any)=>{
          if (res.success) {
            resultList.value = res.data
            let dateArr: any = [], depthArr: any = [], electricityArr: any = [];
            dateArr = res.data.dateTime
            depthArr = res.data.depth
            electricityArr = res.data.electricity

            cementBuildOption.value = {
              title: {
                text: '',
                left: 'center'
              },
              grid: {
                bottom: 80
              },
              toolbox: {
                feature: {
                  dataZoom: {
                    yAxisIndex: 'none'
                  },
                  restore: {}, // 刷新
                  saveAsImage: {} // 下载为图片
                }
              },
              tooltip: {
                trigger: 'axis',
                axisPointer: {
                  type: 'cross',
                  animation: false,
                  label: {
                    backgroundColor: '#505765'
                  }
                }
              },
              legend: {
                data: ['总深度', '电流'],
                left: 10
              },
              dataZoom: [
                {
                  show: true,
                  realtime: true,
                  start: 0,
                  end: 100
                },{
                  type: 'inside',
                  realtime: true,
                  start: 0,
                  end: 100
                }
              ],
              xAxis: [
                {
                  type: 'category',
                  boundaryGap: false,
                  axisLine: { onZero: false },
                  // prettier-ignore
                  data: dateArr
                }
              ],
              yAxis: [
                {
                  name: '总深度(m)',
                  type: 'value'
                },
                {
                  name: '电流(A)',
                  nameLocation: 'start',
                  alignTicks: true,
                  type: 'value',
                  inverse: true
                }
              ],
              series: [
                {
                  name: '总深度',
                  type: 'line',
                  areaStyle: {},
                  lineStyle: {
                    width: 1
                  },
                  emphasis: {
                    focus: 'series'
                  },
                  // prettier-ignore
                  data: depthArr
                },
                {
                  name: '电流',
                  type: 'line',
                  yAxisIndex: 1,
                  areaStyle: {},
                  lineStyle: {
                    width: 1
                  },
                  emphasis: {
                    focus: 'series'
                  },
                  data: electricityArr
                }
              ]
            }
          }else {
            message.info(res.msg)
          }
        })
      }else {
        cementBuildOption.value = {
          title: {
            text: '',
            left: 'center'
          },
          grid: {
            bottom: 80
          },
          toolbox: {
            feature: {
              dataZoom: {
                yAxisIndex: 'none'
              },
              restore: {}, // 刷新
              saveAsImage: {} // 下载为图片
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              animation: false,
              label: {
                backgroundColor: '#505765'
              }
            }
          },
          legend: {
            data: ['总深度', '电流'],
            left: 10
          },
          dataZoom: [
            {
              show: true,
              realtime: true,
              start: 0,
              end: 100
            },{
              type: 'inside',
              realtime: true,
              start: 0,
              end: 100
            }
          ],
          xAxis: [
            {
              type: 'category',
              boundaryGap: false,
              axisLine: { onZero: false },
              // prettier-ignore
              data: []
            }
          ],
          yAxis: [
            {
              name: '总深度(m)',
              type: 'value'
            },
            {
              name: '电流(A)',
              nameLocation: 'start',
              alignTicks: true,
              type: 'value',
              inverse: true
            }
          ],
          series: [
            {
              name: '总深度',
              type: 'line',
              areaStyle: {},
              lineStyle: {
                width: 1
              },
              emphasis: {
                focus: 'series'
              },
              // prettier-ignore
              data: []
            },
            {
              name: '电流',
              type: 'line',
              yAxisIndex: 1,
              areaStyle: {},
              lineStyle: {
                width: 1
              },
              emphasis: {
                focus: 'series'
              },
              data: []
            }
          ]
        }
      }
    }

    const selectSectionClick =()=>{
      isRedrawAction.value = isRedrawKind.value
      getCellBaseInfoList(null)
    }

    const  changeSelect = (val:any)=>{
      isRedrawKind.value = false
      let sectionsAry = sections.value
      if (val>=1){
        let selectDict = sectionsAry[val-1]
        let craftAry = selectDict["craft"]
        for (let i = 0; i <craftAry.length ; i++) {
          let craftDict = craftAry[i]
          if (craftDict["kind"]==23){
            //当前下拉列表有权限
            isRedrawKind.value = true
          }
        }
      }
    }


    // 打开轨迹回放弹框
    const openPlaybackModal = (cellId: number) => {
      removeDraw()
      playbackInfo.showPbModal = true
      playbackInfo.cellId = cellId
      nextTick(() => {
        initMap2()
      })
    }

    const closePlaybackModal = () => {
      playbackInfo.showPbModal = false;
     clearLayer()

    }

    // 初始化轨迹回放地图
    const initMap2 = () => {
      let mapSource: Sources = {
        google: {
          type: 'raster',
          tiles: [
            config.map.baseLayer1URL,
            config.map.baseLayer2URL,
            config.map.baseLayer3URL
          ],
          tileSize: 256
        }
      }
      if (!newMap) {
        newMap = new mapboxgl.Map({
          container: 'trackpb-box',
          style: {
            version: 8,
            sources: mapSource,
            layers: [
              {
                id: 'googleTiles1',
                type: 'raster',
                source: 'google'
              }
            ]
          },
          minZoom: 5,
          maxZoom: 24,
          center: config.map.center,
          zoom: config.map.zoom,
          attributionControl: false
        })

      }
      trackMap = {
        isPlay: false,
        counter: 0,
        maxSetps: 0,
        draws: new Array(),
        map: newMap
      }
      trackMap.map.on('load', () => {
        trackMap.map.addLayer({
          id: 'air1',
          type: 'raster',
          source: {
            type: 'raster',
            tiles: [config.map.airUrl]
          }
        })
        trackMap.map.addSource('redLineSource', {
          type: 'geojson',
          data: redLine
        })
        trackMap.map.addLayer({
          id: 'redLineLayer',
          type: 'line',
          source: 'redLineSource',
          layout: {},
          paint: {
            'line-color': '#ff0000',
            'line-width': 2,
            'line-opacity': 1
          }
        })
      })
    }

    const clearLayer = ()=>{
      stopClick()
      for (let i = 0; i < routeId.length; i++) {
        if (trackMap.map.getSource(routeId[i])){
          trackMap.map.removeLayer(routeId[i]).removeSource(routeId[i])
        }
      }
      for (let i = 0; i < realRouteId.length; i++) {
        if (trackMap.map.getSource(realRouteId[i])) {
          trackMap.map.removeLayer(realRouteId[i]).removeSource(realRouteId[i])
        }
      }
      routeId.length =0
      realRouteId.length =0
      trackMap.draws.length =0
    }

    const getPath = (cellId: number, startTime: any, endTime: any) => {
      clearLayer()
      axios
          .post('/cement/findHistoryByCell', {
            cellId: cellId,
            startTime: moment(startTime.toDate()).format('YYYY-MM-DD HH:mm:ss'),
            endTime: moment(endTime.toDate()).format('YYYY-MM-DD HH:mm:ss')
          })
          .then((res: any) => {
            if (res.success) {
              if (res.data.realData == null) {
                message.info('当前时间段暂无数据')
              } else {
                let mydata = res.data.realData
                let deviceIds = mydata.map((item: any) => item.deviceId)
                deviceIds = Array.from(new Set(deviceIds))
                deviceIds.forEach((item1: any) => {
                  trackMap.draws.push({
                    deviceId: item1,
                    newRouteGeoJson: null,
                    steps: 0,
                    aLength: 0,
                    routeGeoJson: {
                      type: 'FeatureCollection',
                      features: [
                        {
                          type: 'Feature',
                          geometry: {
                            type: 'MultiPoint',
                            coordinates: mydata
                                .filter((item2: any) => item2.deviceId == item1)
                                .map((item3: any) => [
                                  item3.longitude,
                                  item3.latitude,
                                ])
                          }
                        }
                      ]
                    },
                    realRouteGeoJson: {
                      type: 'FeatureCollection',
                      features: [
                        {
                          type: 'Feature',
                          geometry: {
                            type: 'MultiPoint',
                            coordinates: []
                          }
                        }
                      ]
                    },
                  })
                })
              }
            } else {
              message.info('暂无数据')
            }
          })
    }

    const startClick = () => {
      if (!trackMap.isPlay) {
        setRouteData()
        trackMap.isPlay = true
        animate()
      }
    }

    const pauseClick = () => {
      trackMap.isPlay = false
      animate()
    }

    const stopClick = () => {
      trackMap.isPlay = false
      trackMap.counter = 0
      animate()
    }

    const setRouteData = () => {
      trackMap.map.getStyle().layers.forEach((item: any) => {
        if (item.id.indexOf('_') >= 0) {
          trackMap.map.removeLayer(item.id).removeSource(item.id)
        }
      })
      if (trackMap.draws.length == 0) return
      trackMap.draws.forEach((item: any, index: number) => {
        item.newRouteGeoJson = resetRoute(
            item.routeGeoJson.features[0],
        )
        console.log(" item.newRouteGeoJson.lentgh")
        console.log(trackMap.maxSetps)
        routeId.push(`route_${index}`)
        realRouteId.push(`realRoute_${index}`)
        addRoutelayer(`route_${index}`, item.routeGeoJson) // 添加轨迹线图层
        addRealRouteSource(`realRoute_${index}`, item.realRouteGeoJson) // 添加实时轨迹线图层
      })
    }
    const addRoutelayer = (layerName: string, data: number) => {
      trackMap.map.addLayer({
        id: layerName,
        type: 'circle',
        source: {
          type: 'geojson',
          // lineMetrics: true,
          data: data
        },
        paint: {
          'circle-radius': 3,
          'circle-color': '#D0D0D0'
        }
      })
    }

    // 添加实时轨迹线
    const addRealRouteSource = (layerName: string, data: number) => {
      trackMap.map.addLayer({
        id: layerName,
        type: 'circle',
        source: {
          type: 'geojson',
          // lineMetrics: true,
          data: data
        },
        paint: {
          'circle-radius': 3,
          'circle-color': '#00f000'
        }
      })
    }

    const animate = () => {

      trackMap.draws.forEach((item: any, index: number) => {
        if (trackMap.counter > item.newRouteGeoJson.geometry.coordinates.length) return
        if (trackMap.counter == 0) {
          item.realRouteGeoJson.features[0].geometry.coordinates = []
        } else if (trackMap.counter !== 0) {
          item.realRouteGeoJson.features[0].geometry.coordinates.push(
              item.newRouteGeoJson.geometry.coordinates[trackMap.counter-1]
          )
          console.log("push")
          console.log(item.realRouteGeoJson)
        }

        trackMap.map
            .getSource(`realRoute_${index}`)?.setData(item.realRouteGeoJson)

      })

      if (trackMap.isPlay) {
        requestAnimationFrame(animate)
        trackMap.counter = trackMap.counter + 1
      }

    }

    const resetRoute = (route: any, ) => {
      var newroute = {
        type: 'Feature',
        geometry: {
          type: 'MultiPoint',
          coordinates: Array<any>()
        }
      }
      console.log("666")
      console.log(route)
      for (let i = 0; i < route.geometry.coordinates.length ; i++) {
        newroute.geometry.coordinates.push(route.geometry.coordinates[i])
      }
      return newroute
    }

    // 看板跳转
    const getQueryVariable=(variable:any)=>{
      // var query = window.location.search;
      var query = window.location.hash.split("?")[1];
      // if(query.indexOf('?') === -1) return null; //如果url中没有传参直接返回空
      //key存在先通过search取值如果取不到就通过hash来取
      if (query != undefined) {
        // query = query.substr(1) || window.location.hash.split("?")[1];
        var vars = query.split("&");
        for (var i = 0;i < vars.length;i++) {
          var pair = vars[i].split("=");
          if(pair[0] == variable){return pair[1];}
        }
      }
      return null
    }
    const getParameters = () =>{
      let id:any = getQueryVariable('id')
      let type:any = getQueryVariable('type')
      if (id != null && type != null) {
        zoneId.value = parseInt(id)
        zoneKind.value = parseInt(type)
      }
    }

    onMounted(()=>{
      if(sections.value.length>0){
        cellQueryFormState.value.sections[0].sectionId = sections.value[0].sectionId

        let sectionsAry = sections.value
        let selectDict = sectionsAry[0]
        let craftAry = selectDict["craft"]
        for (let i = 0; i <craftAry.length ; i++) {
          let craftDict = craftAry[i]
          if (craftDict["kind"]==23){
            //有权限
            isRedrawKind.value = true
            isRedrawAction.value =true
          }else {
          }
        }
        getCellBaseInfoList(null).then(() => {
          // 看板跳转
          getParameters()
          if (zoneId.value != null || zoneKind.value != null) {
            let cell = {
              cellId: zoneId.value,
              kind: zoneKind.value
            }
            let f1 = getCellBaseInfo(cell)
            let f2 = getCellWorkMachineryByCellId(cell)
            Promise.all([f1,f2]).then((res:any)=>{
              // 1.持久化数据
              // 清除旧图层&数据源
              maps.LayerList.forEach((item:any)=>{
                if(maps.map.getLayer(item)){
                  maps.map.removeLayer(item)
                  maps.LayerList.delete(item)
                }
              })
              maps.sourceList.forEach((item:any)=>{
                if(maps.map.getSource(item)) maps.map.removeSource(item)
              })
              // 添加默认图层
              let layerInfo:MapLayerRequestInfo = {
                cellId:inCellBaseInfo.value.cellId,
                craft:"HaErBin-JBZ",  // cement-修改-工艺代码---已修改
                type:"border"
              }
              addSource(layerInfo)
              addLayer(layerInfo)

              // 2.实时数据
              // 先清除旧的实时显示相关的数据,图层,marker
              realMapInfo.deviceList.forEach((item:any)=>{
                item.deviceMarker.remove()
              })
              realMapInfo.deviceList = new Array<MapDeviceInfo>()
              MqttService.unsubscribe(realMapInfo.subscribeList)
              realMapInfo.subscribeList = new Array<string>()
              realMapInfo.realSource.features = new Array<any>()
              if(maps.map.getLayer(realMapInfo.realLayerName)) maps.map.removeLayer(realMapInfo.realLayerName)
              if(maps.map.getSource(realMapInfo.realSourceName)) maps.map.removeSource(realMapInfo.realSourceName)

              // 订阅新选定仓面的设备数据
              workListInfo.value.workList = res[1].data
              res[1].data.forEach((item:any)=>{
                let el = document.createElement("div")
                el.className = "device-cement"
                el.innerText = `${item.deviceName}`

                realMapInfo.deviceList.push({
                  deviceId:item.deviceId,
                  deviceInfo:item,
                  deviceMarker:new mapboxgl.Marker(el).setLngLat([0,0]).setOffset(new mapboxgl.Point(86,-16)).addTo(maps.map)
                })
                MqttService.subscribe(`${config.craft.cement.mqtt.topic}${item.deviceSn}`) // cement-修改-mqtt
              })

              // 3.操作界面
              mapControl.baseControl = ["border","real_cement"]
              // 跳转位置
              if (res[0].data.centLat && res[0].data.centLon){
                maps.map.setZoom(17)
                let cellCenter = new mapboxgl.LngLat(res[0].data.centLon, res[0].data.centLat);
                mapToCell(cellCenter)
              }
            })
          }
        })
      }
      // 加载地图
      initMap()
      // 初始化mqtt
      MqttService.init(
          `${config.craft.cement.mqtt.ip}`, // cement-修改-mqtt---已修改
          new MqttOptions(`${config.craft.cement.mqtt.userName}`, `${config.craft.cement.mqtt.password}`),
          (topic:any, msg:any) => {
            /**
             * 车辆图层
             * 先判断当前车辆在数据源中的位置
             * 若不存在车辆,则新增
             * 若存在,则修改当前记录
             */
            msg = JSON.parse(msg.toString())
            console.log(`socket=1${JSON.stringify(msg)},${topic}`)
            pointRealTimeInfo.value = msg
            console.log(msg.deviceId)
            let deviceListIndex = realMapInfo.deviceList.findIndex((item:any)=>{
              return item.deviceId == msg.deviceId
            })
            if(deviceListIndex < 0) return

            realMapInfo.deviceList[deviceListIndex].deviceMarker.getElement().innerText = `${realMapInfo.deviceList[deviceListIndex].deviceInfo.deviceName},${msg.depth.toFixed(2)}m`
            realMapInfo.deviceList[deviceListIndex].deviceMarker.setLngLat([msg.longitude,msg.latitude])

            realMapInfo.realSource.features.push({
              type: "Feature",
              geometry: {
                type: "Point",
                coordinates: [msg.longitude,msg.latitude]
              }
            })

            if(maps.map.getLayer(realMapInfo.realLayerName)) maps.map.removeLayer(realMapInfo.realLayerName)
            if(maps.map.getSource(realMapInfo.realSourceName)) maps.map.removeSource(realMapInfo.realSourceName)

            maps.map.addSource(realMapInfo.realSourceName,{type:'geojson',data:realMapInfo.realSource})
            maps.map.addLayer({
              id: realMapInfo.realLayerName,
              type: "circle",
              source: realMapInfo.realSourceName,
              paint: {
                'circle-radius': {
                  'base': 2,
                  'stops': [[0,0],[20,10]]
                },
                'circle-color': "#0CDB34"
              }
            })
            maps.LayerList.add(realMapInfo.realLayerName)
          }
      )
    })



    onBeforeUnmount(()=>{
      // 关闭mqtt
      MqttService.unsubscribe(realMapInfo.subscribeList);
      MqttService.end();
      // 移除地图
      maps.map.remove()
    })

    return {

      ranges: {
        近七日: [
          moment()
              .startOf('day')
              .subtract(1, 'weeks'),
          moment()
        ],
        本月: [moment().startOf('month'), moment()]
      },
      sections,
      setHeight,
      kindDict,
      cellStatusDict,
      handleCell,
      ...toRefs(mapControl),
      clickMapControl,
      clickMapEvent,
      workListInfo,
      deviceTypeDict,
      cellQueryFormRef,
      cellQueryFormState,
      cellBaseInfoList,
      inCellBaseInfo,
      getCellBaseInfoList,
      setCellStatus,

      ...toRefs(exAreaInfo),
      openExAreaModal,
      addExArea,
      saveExArea,
      delExArea,
      openFileModal,
      readBorderFile,
      drawTheBorder,
      isDrawSave,
      saveDrawArea,

      moment,
      resultList,
      cementBuildOption,
      pointRealTimeInfo,
      cementRealTimeInfo,
      getCementBuildInfo,
      changeSelect,
      selectSectionClick,
      playbackInfo,
      playbackDate,
      openPlaybackModal,
      getPath,
      startClick,
      pauseClick,
      stopClick,
      closePlaybackModal,

      // 看板跳转
      zoneId,
      zoneKind,
      getParameters
    }
  },
  components: { SModal, VueEcharts, EditOutlined, CloseOutlined,SaveOutlined,DeleteOutlined, CheckOutlined,
    HistoryOutlined}
})
</script>

<style scoped lang="scss">
::v-deep .mapboxgl-control-container{
  display: block;
  .mapboxgl-ctrl-bottom-left{
    display: none;
  }
}
::v-deep .mapboxgl-ctrl {
  display: block !important;
}
.draw-save {
  position: absolute;
  top:  80px;
  left: 10px;
  text-align: center;
}
.monitor-box {
  display: flex;
  width: 100%;
  height: 100%;
  .left-box {
    display: flex;
    flex-direction: column;
    width: 495px;
    height: 100%;
    .control-box {
      display: flex;
      width: 100%;
      height: 262px;
      .search-box {
        width: 235px;
        height: 100%;
        padding: 12px 17px;
        box-sizing: border-box;
        ::v-deep label {
          color: #666666;
        }
        ::v-deep .ant-form-item {
          display: flex;
          margin-bottom: 10px;
        }
        ::v-deep .ant-form-item-control-wrapper {
          flex: 1;
        }
        ::v-deep .ant-select {
          width: 100%;
        }
      }
      .map-control {
        width: 240px;
        height: 100%;
        margin-left: 20px;
        padding: 10px 17px;
        box-sizing: border-box;
        .map-control-title {
          color: #333333;
          font-weight: bold;
        }
        .map-control-title:nth-of-type(n + 2) {
          display: inline-block;
          margin-top: 16px;
        }
        ::v-deep .ant-checkbox-group {
          .ant-checkbox-wrapper {
            width: 100px;
            margin-right: 0px;
            border: 2px solid #1890ff;
            box-sizing: border-box;
            border-radius: 2px;
            color: #1890FF;
            font-size: 12px;
            margin-top: 8px;
            padding: 2px 2px;
            > span:nth-of-type(n + 1) {
              padding-left: 4px;
              padding-right: 4px;
            }
          }
          .ant-checkbox-wrapper:nth-child(odd) {
            margin-right: 6px;
          }
          .ant-checkbox-inner {
            border: 1px solid #1890ff;
          }
        }
      }
    }
    .cell-table-box {
      display: flex;
      flex-direction: column;
      width: 495px;
      flex: 1;
      margin-top: 20px;
      padding: 0 13px;
      .table-box-header {
        color: #333333;
        font-size: 18px;
        font-weight: bold;
        padding: 18px 0 10px 10px;
      }
      .table-box-center {
        width: 100%;
        flex: 1;
      }
      ::v-deep .table-icon-box {
        display: flex;
        justify-content: space-around;
        > div:hover {
          color: #1677ff;
        }
      }
    }
  }
  .right-box {
    display: flex;
    flex-direction: column;
    flex: 1;
    height: 100%;
    margin-left: 20px;
    .base-info-box {
      width: 100%;
      height: 82px;
      padding: 14px 0 0;
    }
    .map-box {
      position: relative;
      flex: 1;
      width: 100%;
      height: 100%;
      margin-top: 20px;
      box-sizing: border-box;
      .point-info {
        z-index: 1;
        .point-header {
          display: flex;
          width: 100%;
          height: 52px;
          line-height: 52px;
          padding: 0 16px;
          box-sizing: border-box;
          justify-content: space-between;
          border-bottom: 1px solid #eeeeee;
          > span {
            font-size: 18px;
            font-weight: 600;
            color: #333333;
          }
          ::v-deep .anticon {
            line-height: 52px;
          }
        }
      }
      .point-info {
        display: flex;
        flex-direction: column;
        position: absolute;
        top: 40px;
        right: 232px;
        width: 1191px;
        height: 625px;
        background: #FFFFFF;
        box-shadow: 0px 2px 16px 0px rgba(0, 0, 0, 0.08);
        border-radius: 2px;
        box-sizing: border-box;
        .point-content{
          display: flex;
          flex-direction: column;
          width: 100%;
          height: 100%;
          padding: 15px 20px;
          .info-box {
            display: flex;
            flex-direction: column;
            width: 500px;
            height: 100%;
            .real-time {
              width: 100%;
              height: 246px;
              >span {
                font-size: 14px;
                font-weight: 400;
                color: #666666;
              }
              .info {
                width: 100%;
                height: 216px;
                margin-top: 8px;
                padding: 0 20px;
                background: #F7F9FC;
                ::v-deep .ant-row{
                  width: 100%;
                  line-height: 36px;
                  .ant-col:nth-child(odd){
                    font-size: 14px;
                    font-weight: 600;
                    color: #666666;
                  }
                  .ant-col:nth-child(even){
                    font-size: 14px;
                    font-weight: 400;
                    color: #666666;
                  }
                }
              }
            }
            .pile-forming {
              width: 100%;
              height: 282px;
              margin-top: 15px;
              >span {
                font-size: 14px;
                font-weight: 400;
                color: #666666;
              }
              .info {
                width: 100%;
                height: 252px;
                margin-top: 8px;
                padding: 0 20px;
                background: #F7F9FC;
                ::v-deep .ant-row{
                  width: 100%;
                  line-height: 36px;
                  .ant-col:nth-child(odd){
                    font-size: 14px;
                    font-weight: 600;
                    color: #666666;
                  }
                  .ant-col:nth-child(even){
                    font-size: 14px;
                    font-weight: 400;
                    color: #666666;
                  }
                }
              }
            }
          }
          .option-box {
            display: flex;
            flex-direction: column;
            position: absolute;
            right: 20px;
            flex: 1;
            width: 631px;
            height: 543px;
            //margin-left: 20px;
          }
        }
      }
      .map-event-control {
        display: flex;
        position: absolute;
        top: 5px;
        right: 5px;
        height: 30px;
        background-color: #ffffff;
        border-radius: 3px;
        z-index: 10;
        overflow: hidden;
        .map-control-button {
          width: 90px;
          height: 30px;
          font-size: 14px;
          line-height: 28px;
          text-align: center;
          border: 1px solid #f0f0f0;
          box-sizing: border-box;
          cursor: pointer;
        }
        .map-control-active {
          color: #1890ff;
        }
        .map-control-disable {
          color: #8d8d8d;
        }
      }
      #mapboxgl-box {
        display: flex;
        width: 100%;
        height: calc(100% - 6px);
        box-sizing: border-box;
      }
      .tamp-legend{
        position: absolute;
        display: flex;
        flex-direction: column;
        padding: 8px 2.5px;
        width: 84px;
        height: 72px;
        right: 5px;
        bottom: 12px;
        background: #FFFFFF;
        border-radius: 3px;
        box-sizing: border-box;
        z-index: 1;
        >div{
          display: flex;
          width: 100%;
          height: 28px;
          .legend{
            display: flex;
            justify-content: center;
            align-items: center;
            width: 28px;
            height: 28px;
            >div{
              width: 12px;
              height: 12px;
              border-radius: 50%;
            }
          }
          .legend-title{
            color: #666666;
            line-height: 28px;
            text-align: center;
          }
        }
      }
      .ex-area-btn {
        position: absolute;
        left: 5px;
        bottom: 12px;
        width: 32px;
        height: 32px;
        background: url('../../../assets/image/ex_area.png') center no-repeat;
        background-size: 18px;
        background-color: #e6f1fc;
        border: 1px solid #1677ff;
        box-sizing: border-box;
        z-index: 1;
      }
      .work-list-btn {
        position: absolute;
        left: 42px;
        bottom: 12px;
        width: 32px;
        height: 32px;
        background: url('../../../assets/image/work_list.png') center no-repeat;
        background-size: 18px;
        background-color: #e6f1fc;
        border: 1px solid #1677ff;
        box-sizing: border-box;
        z-index: 1;
      }
    }
  }
}
.smodal-box{
  box-sizing: border-box;
}
.smodal-to-cell{
  width: 100%;
  height: 100%;
}
.ex-area-modal{
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  .ex-table-box{
    flex: 1;
    padding-top: 10px;
  }
  .ex-area-btn-box{
    display: flex;
    justify-content: flex-end;
    width: 100%;
    height: 48px;
  }
}

.pb-track-modal {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;

  .pb-header-box {
    margin-top: 15px;
    height: 50px;
  }

  .pb-track-box {
    position: relative;
    flex: 1;
    width: 100%;
    height: 100%;
    margin-top: 5px;
    box-sizing: border-box;

    .map-event-control {
      display: flex;
      position: absolute;
      top: 5px;
      right: 5px;
      height: 30px;
      background-color: #ffffff;
      border-radius: 3px;
      z-index: 10;
      overflow: hidden;

      .map-control-button {
        width: 90px;
        height: 30px;
        font-size: 14px;
        line-height: 28px;
        text-align: center;
        border: 1px solid #f0f0f0;
        box-sizing: border-box;
        cursor: pointer;
      }

      .map-control-active {
        color: #1890ff;
      }

      .map-control-disable {
        color: #8d8d8d;
      }
    }

    #trackpb-box {
      display: flex;
      width: 100%;
      height: calc(100% - 6px);
      box-sizing: border-box;

      .mapboxgl-canvas {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
